package com.muyan.sys.webscoket.interceptor;

import com.muyan.sys.common.constant.Constants;
import com.muyan.sys.common.core.domain.model.LoginUser;
import com.muyan.sys.common.core.redis.RedisCache;
import com.muyan.sys.common.utils.MessageUtils;
import com.muyan.sys.common.utils.SecurityUtils;
import com.muyan.sys.common.utils.StringUtils;
import com.muyan.sys.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class WebSocketAuthInterceptor {



    @Autowired
    private TokenService tokenService;


    @Autowired
    private RedisCache redisCache;

    public boolean authenticate(ChannelHandlerContext ctx, FullHttpRequest request) {
        try {
            // 获取 token
            String token = request.headers().get(HttpHeaders.Names.AUTHORIZATION);
            if (token == null || token.isEmpty()) {
                log.info("No token provided");
                return false;
            }


            LoginUser loginUser = getLoginUser(request);
            //切换语言
            MessageUtils.changeMessage();
            if (loginUser == null || !StringUtils.isNull(SecurityUtils.getAuthentication())) {
                log.info("Invalid token");
                return false;
            }

            //切换语言
            //   MessageUtils.changeMessage();
            tokenService.verifyToken(loginUser);


            // 验证 token


            // 将用户ID存储在 Channel 的属性中
            ctx.channel().attr(io.netty.util.AttributeKey.valueOf("LoginUser")).set(loginUser);
            return true;
        } catch (Exception e) {
            log.info("Authentication error={}", e);
            log.error("Authentication error={}", e);
            return false;
        }
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(FullHttpRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = tokenService.parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = tokenService.getTokenKey(uuid);
                LoginUser user = redisCache.getCacheObject(userKey);
                return user;
            } catch (Exception e) {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(FullHttpRequest request) {

        String token = request.headers().get(HttpHeaders.Names.AUTHORIZATION);

        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

} 